<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template v-for="boxContent in contentList" :key="boxContent?.title">
        <PackageCard class="card" :boxContent="boxContent" />
      </template>
    </div>
    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"
        @handle-size-change="handleSizeChange"
        @handle-current-change="handleCurrentChange"
      />
      <reportDetail
        ref="addOrUpdateRef"
        :dialogDatas="dialogDatas"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'APMReport' }); //AMP报告管理
import { reactive, ref, onMounted, computed, watch } from 'vue';
import reportDetail from "@/views/APMReport/components/add-or-update/index.vue";
import { Detail } from './components/index';
import { useTable } from '@/hooks/useTable';
import {
  getPageRequest,
  getProjectRequest,
  getInfoRequest,
  getExportRequest,
  getCategoryRequest,
  getBannerRequest,
  userReportExportListRequest,
} from '@/api/APMReport';
import {
  orgOptionsRequest,
  getEnumListRequest,
  getCheckPointsOptionsRequest,
  getHealthDoctorOptionsRequest
} from '@/api/common';
import { useRouteStore } from '@/store';
import { JqTable } from '@/components/Table/index';
import { PackageCard } from '@/components/PackageCard/index';
import type { FormInstance } from 'element-plus';
import APMReport from '@/router/modules/APMReport';
import { useRoute, useRouter } from 'vue-router';
// import type { IUserItem } from '@/api/user/type';
const routeStore = useRouteStore();

/* 表单查询 */
const handleSearch = async (searchFormParamsDatats: {}) => {
  if (searchFormParamsDatats.doctorId instanceof Array) {
    searchFormParamsDatats.doctorId = '';
  }
  if (searchFormParamsDatats.checkPoint instanceof Array) {
    searchFormParamsDatats.checkPoint = '';
  }
  Object.assign(searchFormParams, searchFormParamsDatats);
  await getList();
};
let orgIdDatas = reactive([]); //归属组织下拉数据
let checkPointsOptionsDatas = reactive({}); //归属检测点下拉数据
let healthDoctorOptionsDatas = reactive({}); //归属健康顾问下拉数据
let checkPointsOptionsDatasForForm = reactive({}); //归属检测点下拉数据(数据筛选)


const addOrUpdateRef = ref();
let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '输入查询',
    placeholder: '报告ID/受检人姓名',
    eName: 'keyword'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'selectson',
    value: '',
    label: '归属健康顾问',
    options: () => {
      return healthDoctorOptionsDatas;
    },
    eName: 'doctorId'
  },
  {
    type: 'selectson',
    value: '',
    label: '归属检测点',
    options: () => {
      return checkPointsOptionsDatasForForm;
    },
    eName: 'checkPoint'
  },
  {
    type: 'date',
    value: '',
    label: '创建时间',
    eName: 'startCreateTime'
  },

]);


let searchFormParams = reactive({
  // deviceQueryReq: {}
}); //查询参数
const tableColumn = reactive([
  //内置
  { label: '报告ID', prop: 'id',minWidth: '80' }, //接口缺少字段，待更新？
  { label: '受检者姓名', prop: 'userName',minWidth: '100' },
  { label: '归属组织机构', prop: 'orgName',minWidth: '110' },
  { label: '归属检测点', prop: 'checkPointsName',minWidth: '100' },
  { label: '归属健康顾问', prop: 'doctorName',minWidth: '120' },
  { label: '检测设备ID', prop: 'deviceId',minWidth: '100' },
  { label: '创建时间', prop: 'createTime',minWidth: '180' }
]);
let tableButtons = reactive([
  //来源于数据
  {
    id: 39,
    type: '',
    perms: 'amp:btn:export',
    label: '导出',
    onClick:async () => {
    const params=Object.assign({},searchFormParams,{pageNum: page.page, pageSize: page.pageSize })
      const data: any =  await userReportExportListRequest(params)
      if (data.code === 2000) {
        ElMessage.success('导出成功');
      }
      window.open(data.data);
    }
  },
]);
const currentMenudatas = computed(() => routeStore.currentMenudatas);
interface Row {
  id: number;
  status: number;
  checkPointsId: number;
}
let itemsButtons = reactive([
  //来源于数据
  {
    id: 40,
    type: 'success',
    label: '查看',
    perms: 'amp:btn:view',
    onClick: (row: Row) => {
      // setDialogDefaultDatas(row);
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row
      };
      onAddOrUpdate(dialogDatas);
    }
  }
  // {
  //   id: '3',
  //   type: 'primary',
  //   label: '人工解读',
  //   onClick: (row: []) => {
  //     dialogDatas = {
  //       title: '人工解读',
  //       type: 'edit',
  //       datas: dialogForConfigDatas
  //     };
  //     onAddOrUpdate(dialogDatas);
  //   }
  // }
  // {
  //   id: '4',
  //   type: 'primary',
  //   label: '在线随访',
  //   onClick: (row: []) => {
  //     dialogDatas = {
  //       title: '在线随访',
  //       type: 'edit',
  //       datas: dialogForConfigDatas
  //     };
  //     onAddOrUpdate(dialogDatas);
  //     onAddOrUpdate(row);
  //   }
  // },
  // {
  //   id: '4',
  //   type: 'primary',
  //   label: '电话随访',
  //   onClick: (row: []) => {
  //     dialogDatas = {
  //       title: '电话随访',
  //       type: 'edit',
  //       datas: dialogForConfigDatas
  //     };
  //     onAddOrUpdate(dialogDatas);
  //     onAddOrUpdate(row);
  //   }
  // },
  // {
  //   id: '4',
  //   type: 'primary',
  //   label: '干预方案',
  //   onClick: (row: []) => {
  //     dialogDatas = {
  //       title: '干预方案',
  //       type: 'edit',
  //       datas: dialogForConfigDatas
  //     };
  //     onAddOrUpdate(dialogDatas);
  //     onAddOrUpdate(row);
  //   }
  // }
]);
const contentList = reactive([
  {
    title: '本月新增报告数',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '报告总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '最近3个月报告数',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  },
  {
    title: '最近6个月报告数',
    number: '',
    bgUrl: 'Bg4.png',
    iconUrl: 'Icon4.png'
  },
  {
    title: '最近12个月报告数',
    number: '',
    bgUrl: 'Bg5.png',
    iconUrl: 'Icon5.png'
  }
]);
const onAddOrUpdate = (data?: Recordable) => {
  console.log(data);
  
  addOrUpdateRef.value.init(data);
};
let dialogForConfigDatas = reactive([]);
//设置弹出框内表单回显数据
// const setDialogDefaultDatas = (row: any) => {
//   dialogForConfigDatas.forEach((d) => {
//     if (d.type === 'cascader') {
//       d.keys.forEach((key, i) => {
//         d.value.push(row[key]);
//       });
//       return;
//     }
//     d.value = row[d.eName];
//   });
// };
let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getPageRequest,
    params: ()=>searchFormParams
  });
  watch(searchForm[1], async(newVal, oldVal) => {//数据筛选
  /* 获取归属检测点数据 */
  if(newVal.value){
  const data: any = await getCheckPointsOptionsRequest({orgId:newVal.value});
  checkPointsOptionsDatasForForm = data.data;
  }
})
const chanFormValue=(formParamsDatats:{})=>{
  searchFormParams=formParamsDatats
}

//设置弹出框内表单回显数据
const setDialogDefaultDatas = async (row: { checkPointsId:number }) => {
  const data: any = await getCheckPointsDetailRequest({ checkPointsId:row.checkPointsId});//获取弹出框回显数据
  const checkPoints: any = await getCheckPointsOptionsRequest({orgId:data.data.orgId});//根据组织id查询检测点下拉数据
  checkPointsOptionsDatas = checkPoints.data;
  dialogForConfigDatas.forEach((d) => {
    if (d.type === 'cascader') {
      d.keys.forEach((key, i) => {
        d.value.push(data.data[key]);
      });
      return;
    }
    d.value = data.data[d.eName];
  });
};
const onDelete = () => {
  ElMessageBox.confirm('您确认要删除当前项吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '只是个demo！'
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作'
      });
    });
};
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams={}
  // orgIdDatas=[]
  healthDoctorOptionsDatas=[]
  checkPointsOptionsDatasForForm=[]
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
 getList();
};
//根据数据返回按钮信息控制权限
/* params
{
  datas:本地配置的按钮数据（tableButtons/itemsButtons)
}
*/
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
/* 归属组织 */
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
};
// /*列表-报告查询 */
// const getPageDatas = async (datas: {}) => {
//   const data: any = await getPageRequest(datas);
// };
/*项目详情 */
const getProjectDatas = async (datas: {}) => {
  const data: any = await getProjectRequest(datas);
};
/*报告详情 */
const getInfoDatas = async (datas: {}) => {
  const data: any = await getInfoRequest(datas);
};
/*export */
const getExportDatas = async (datas: {}) => {
  const data: any = await getExportRequest(datas);
};
/*报告分类 */
const getCategoryRequestDatas = async (datas: {}) => {
  const data: any = await getCategoryRequest(datas);
};
/* 获取归属检测点数据 */
// const getCheckPointsOptionsDatas = async () => {
//   const data: any = await getCheckPointsOptionsRequest({});
//   checkPointsOptionsDatas = data.data;
// };
/* 获取归属健康顾问数据 */
const getHealthDoctorOptionsDatas = async (datas: {}) => {
  const data: any = await getHealthDoctorOptionsRequest(datas);
  healthDoctorOptionsDatas = data.data;
};

/*健康报告导航 */
const getBannerDatas = async () => {
  const data: any = await getBannerRequest({});
  const statisticsDatas = data.data;
  contentList[0].number = statisticsDatas.newReport;
  contentList[1].number = statisticsDatas.allReport;
  contentList[2].number = statisticsDatas.threeMonthsReport;
  contentList[3].number = statisticsDatas.sixMonthsReport;
  contentList[4].number = statisticsDatas.oneYearReport;
};

onMounted(() => {
  getOrgOptionsDatas();
  getBannerDatas();
  if(!currentMenudatas.value) {
    return
  }
  // getCheckPointsOptionsDatas();
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});
//监听组织id,逻辑为组织id与健康顾问联动
watch(
  () => searchForm[1].value,
  () => {
    const orgId = searchForm[1].value;
    if (orgId) {
      getHealthDoctorOptionsDatas({ orgId });
    }
  }
);

// 监听组织（form表单）
// watch(
//   () => dialogForBaseFormDatas[2].value,
//   (newVal, oldVal) => {
//     dialogForBaseFormDatas[4].value = '';
//     getFormRoleOptions(newVal);
//   }
// );
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  > .card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;
    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
